/*jshint esversion: 9 */
/**
 * http请求配置
 */
import axios from "axios";
import Const from "./Const";
import { userData as userDataStore } from "@/store/User";
import {
    messageSuccess,
    messageError,
    confirm,
} from "@/action/MessagePrompt";
import router from '@/router';

export const service = axios.create({  //可创建多个 axios实例
    baseURL: Const.baseApiURL, //设置公共的请求前缀
    timeout: Const.timeout, //超时终止请求
});

service.interceptors.request.use(
    config => {
        const userData = userDataStore();
        config.headers = config.headers || {};
        // 从用户数据中获取token
        if (userData.userInfo.token) {
            config.headers['Authorization'] = `Bearer ${userData.userInfo.token}`;
        }
        return config;
    },
    () => {
        return Promise.reject({
            msg: '请求发生错误，请稍后再试',
        });
    },
);

let modelShow = false;
service.interceptors.response.use(
    response => {
        const data = response.data;
        
        // 对于DELETE请求，通常返回204 No Content或200 OK，可能没有data字段
        if (response.config.method.toLowerCase() === 'delete') {
            // DELETE请求成功，返回一个表示成功的对象
            return { success: true, message: '删除成功' };
        }
        
        // console.log(data);
        if (!data) {
            return Promise.reject({
                msg: '请求发生错误',
            });
        }
        const success = data.success;

        if (success !== false) {
            return response.data;
        } else {
            switch (response.status) {
                case 401: //表示需要重新登录
                    if (!modelShow) {
                        modelShow = true;
                        confirm(
                            '登录已经失效，是否重新登录？',
                            '登录失效',
                            {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning',
                            },
                        )
                            .then(() => {
                                router.push({
                                    path: '/login',
                                });
                            }).catch(() => { }).finally(() => {
                                modelShow = false;
                            });
                    }
                    return Promise.reject(data);
                default:
                    return Promise.reject(data);
            }
        }
    },
    () => { //数据请求发生错误
        return Promise.reject({
            msg: '请求发生错误，请稍后再试',
        });
    },
);